import click
import json
import os
import sys
from datetime import datetime
import pandas as pd

# 添加项目根目录到sys.path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from quantitative.quant_factory import QuantAnalyzerFactory

@click.group()
def cli():
    """股票量化分析命令行工具"""
    pass

@cli.command()
@click.option('--config', '-c', required=True, help='配置文件路径')
@click.option('--stock', '-s', required=True, help='股票代码')
@click.option('--analyzer', '-a', default='hikyuu', type=click.Choice(['hikyuu', 'qlib']), help='分析框架')
def analyze(config, stock, analyzer):
    """分析单只股票"""
    # 加载配置
    with open(config, 'r', encoding='utf-8') as f:
        config_data = json.load(f)
    
    # 创建分析器
    factory = QuantAnalyzerFactory(config_data)
    quant_analyzer = factory.get_analyzer(analyzer)
    
    # 执行分析
    click.echo(f"使用 {analyzer} 分析股票 {stock}...")
    
    if analyzer == 'hikyuu':
        result = quant_analyzer.analyze_stock(stock)
    else:  # qlib
        result = quant_analyzer.get_market_analysis(stock)
    
    # 打印结果
    click.echo(json.dumps(result, indent=2, ensure_ascii=False))

@cli.command()
@click.option('--config', '-c', required=True, help='配置文件路径')
@click.option('--stock', '-s', required=True, help='股票代码')
@click.option('--analyzer', '-a', default='hikyuu', type=click.Choice(['hikyuu', 'qlib']), help='分析框架')
@click.option('--start-date', '-sd', default=None, help='回测开始日期 (YYYY-MM-DD)')
@click.option('--end-date', '-ed', default=None, help='回测结束日期 (YYYY-MM-DD)')
@click.option('--strategy', '-st', default='ma_cross', help='策略类型')
def backtest(config, stock, analyzer, start_date, end_date, strategy):
    """回测股票策略"""
    # 加载配置
    with open(config, 'r', encoding='utf-8') as f:
        config_data = json.load(f)
    
    # 创建分析器
    factory = QuantAnalyzerFactory(config_data)
    quant_analyzer = factory.get_analyzer(analyzer)
    
    # 设置默认日期
    if not start_date:
        start_date = (datetime.now() - pd.Timedelta(days=365)).strftime('%Y-%m-%d')
    if not end_date:
        end_date = datetime.now().strftime('%Y-%m-%d')
    
    # 执行回测
    click.echo(f"使用 {analyzer} 回测股票 {stock}，策略：{strategy}...")
    
    if analyzer == 'hikyuu':
        result = quant_analyzer.backtest(stock, start_date, end_date, strategy)
        # 打印回测结果摘要
        click.echo("\n回测结果摘要:")
        click.echo(f"开始日期: {result['summary']['start_date']}")
        click.echo(f"结束日期: {result['summary']['end_date']}")
        click.echo(f"总收益率: {result['summary']['total_return']:.2f}%")
        click.echo(f"年化收益率: {result['summary']['annual_return']:.2f}%")
        click.echo(f"最大回撤: {result['summary']['max_drawdown']:.2f}%")
        click.echo(f"胜率: {result['summary']['win_rate']:.2f}%")
        click.echo(f"总交易次数: {result['summary']['total_trades']}")
        click.echo(f"盈利交易: {result['summary']['win_trades']}")
        click.echo(f"亏损交易: {result['summary']['lose_trades']}")
        click.echo(f"夏普比率: {result['summary']['sharpe_ratio']:.2f}")
    else:  # qlib
        # Qlib先训练模型
        click.echo("训练预测模型...")
        quant_analyzer.train_model(stock, start_date, end_date)
        
        # 回测策略
        result = quant_analyzer.backtest_strategy(stock, start_date, end_date, 'topk')
        
        # 打印回测结果
        click.echo("\n回测结果摘要:")
        click.echo(f"总收益率: {result['report']['return']*100:.2f}%")
        click.echo(f"年化收益率: {result['report']['annual_return']*100:.2f}%")
        click.echo(f"夏普比率: {result['report']['sharpe']:.2f}")
        click.echo(f"最大回撤: {result['report']['max_drawdown']*100:.2f}%")

@cli.command()
@click.option('--config', '-c', required=True, help='配置文件路径')
def init_qlib_data(config):
    """初始化Qlib数据"""
    # 加载配置
    with open(config, 'r', encoding='utf-8') as f:
        config_data = json.load(f)
    
    import qlib
    from qlib.data.data import GetData
    
    # 初始化Qlib
    qlib_data_path = config_data.get('qlib', {}).get('qlib_data_path', '~/.qlib/qlib_data/cn_data')
    click.echo(f"初始化Qlib数据，路径: {qlib_data_path}")
    
    try:
        qlib.init(provider_uri=qlib_data_path)
        # 检查是否能正常获取数据
        data = GetData().get_data(stock_list=["SH000001"], date_range=[datetime.now().strftime('%Y-%m-%d')])
        click.echo("Qlib数据初始化成功!")
    except Exception as e:
        click.echo(f"Qlib数据初始化失败: {str(e)}")
        click.echo("请参考Qlib文档进行数据准备: https://qlib.readthedocs.io/en/latest/start/initialization.html")

if __name__ == '__main__':
    cli() 